<?php
/**
 *并发测试
 */
namespace app\share\controller;

use app\share\model\Store;
use Redis\RedisAction;

class Order
{
    public function __construct()
    {
        $this->redis = new RedisAction();
        $this->order = new \app\share\model\Order();
        $this->store = new Store();
    }

    /**
     * 后端把库存循环到list队列中
     */
    public function pushStock()
    {
        #抢购数量,目前假设为10,后面需要和数据库库存进行比较合理设置
        #直接计算库存数量,全部秒杀
        $number = $this->store->getNumber(2);
        for ($i = 0; $i < $number; $i++)
        {
            $this->redis->lPush('goods_number',1);
        }
        $data['len'] = $this->redis->lLen("goods_number");
        returnJson(200,"success",$data);
    }
    /**
     *生成订单号
     */
    private function buildOrderNo()
    {
        return date('ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }
    #下单前判断redis队列库存量
    public function order()
    {
        $id = 2;
        $store = $this->store->goodsInfo($id);

        $data['sku_id']   = $store['sku_id'];
        $data['user_id']  = rand(1,10000);
        $data['goods_id'] = $store['goods_id'];
        $data['price']    = $store['price'];
        $data['number']   = 1;#抢购时, 每次买一件商品
        $count = $this->redis->rPop("goods_number");
        if( $count == false )
        {
            returnJson(-2004,"商品售罄");
        }
        $data['order_sn'] = $this->buildOrderNo();
        #订单入库
        $this->order->orderSave($data);
        #库存减少
        $this->store->updateNumber($id);
    }

}